﻿using Decision.athen;
using Decision.BusinessLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            if (Request.QueryString["logout"] != null)
            {
                UserAthen.UserLogin = null;
            }

            if (UserAthen.UserLogin != null)
            {
                Util.jsRedirect(this.Page, "index.aspx");
            }
        }
    }
    protected void bt_Login_Click(object sender, EventArgs e)
    {
        if (!validateRequireForm())
        {
            return;
        }

        if(!isLogin())
        {
            Util.jsAlert(this.Page, "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง");
            return;
        }

        if(UserAthen.UserLogin.IS_ACTIVE == null || !(Boolean)UserAthen.UserLogin.IS_ACTIVE)
        {
            Util.jsAlert(this.Page, "บัญชีผู้ใช้ถูกระงับการใช้งาน");
            return;
        }

        Util.jsRedirect(this.Page, "index.aspx");
    }

    private bool isLogin()
    {
        try
        {

            ECT_USER user = DCSFactory.CreateECTUserFactory().GetLogin(txt_userName.Text, Util.EncryptString(txt_Passwprd.Text));

            if (user != null) 
            {
                UserAthen.UserLogin = user;
            }

            return user != null;

        }
        catch (Exception ex)
        {
            Util.jsConsole(Page, ex.ToString());
        }
        return false;
    }

    private bool validateRequireForm()
    {
        bool isValid = !(txt_userName.Text.Trim() == "" || txt_Passwprd.Text.Trim() == "");

        if (!isValid)
        {
            Util.jsAlert(this.Page, "กรุณาระบุบชื่อผู้ใช้และรหัสผ่าน");
            return false;
        }
        

        return true;

    }
}